package com.azt.front.action.company;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.azt.api.dto.UserMsgDto;
import com.azt.api.pojo.Address;
import com.azt.api.pojo.Role;
import com.azt.api.pojo.User;
import com.azt.api.service.AddressService;
import com.azt.api.service.MsgConfigService;
import com.azt.api.service.UserPermissionService;
import com.azt.api.service.UserService;
import com.azt.front.permission.RequireUser;
import com.azt.front.utils.ContextUtil;
import com.azt.front.utils.Globals;
import com.azt.model.AjaxJson;
import com.azt.model.VerifyCode;
import com.azt.utils.BeanUtils;
import com.azt.utils.PasswordUtil;
import com.azt.utils.PatternUtils;


/** 
 * @ClassName: SafeCenterAction 
 * @Description: 安全中心
 * @author: zhaheng
 * @date: 2016年11月4日 上午10:03:45  
 */
@Controller
@RequestMapping("/safecenter")
public class SafeCenterAction {
	@Autowired
	private UserService userService;
	@Autowired
	private MsgConfigService msgConfigService;
	@Autowired
	private AddressService addressService;
	@Autowired
	private UserPermissionService userPermissionService;
	/**首页账户设置菜单链接**/
	@RequireUser
	@RequestMapping("/AccountSetting")
	public String AccountSetting(HttpServletRequest request , HttpServletResponse response){
		return "redirect:/safecenter/personalData";
	}
	
	/** 
	 * @Title: personalData 
	 * @Description: 个人资料展示
	 * @param key
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @return: String
	 * @author: 查恒 2016年11月8日 上午10:40:05 
	 */
	@RequireUser
	@RequestMapping("/personalData")
	public String personalData(Integer key,HttpServletRequest request , HttpServletResponse response , Model model){
		User user = ContextUtil.getUser();
		model.addAttribute("user", user);
		
	    return "safecenter/personalData";
	}
	
	
	/** 
	 * @Title: savePersonalData 
	 * @Description: 保存个人资料
	 * @param user
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @return: AjaxJson
	 * @author: 查恒 2016年11月8日 上午11:32:14 
	 */
	@RequireUser
	@ResponseBody
	@RequestMapping("/savePersonalData")
	public AjaxJson savePersonalData(User user,HttpServletRequest request , HttpServletResponse response , Model model){
		try {
			User userById = userService.getUserById(user.getId());
			BeanUtils.copyBeanNotNull2Bean(user, userById);
			userById.setBirthday(user.getBirthday());//生日是能空的
			userService.saveOrUpdate(userById);
			//更新session
			ContextUtil.setUser(user);
		} catch (Exception e) {
			return AjaxJson.error("保存失败");
		}
		
		return AjaxJson.success("保存成功");
	}
	
	
	/** 
	 * @Title: accountSafe 
	 * @Description: 账户中心
	 * @return
	 * @return: String
	 * @author: 查恒 2016年11月7日 下午2:14:29 
	 */
	@RequireUser
	@RequestMapping("/accountSet")
	public String accountSafe(HttpServletRequest request , HttpServletResponse response , Model model){
		User user = ContextUtil.getUser();
		model.addAttribute("user", user);
		return "safecenter/accountSet";
	}
	
	//修改绑定手机  修改绑定邮箱
	@RequireUser
	@RequestMapping("/bindOrReset")
	public String bindOrReset(Integer reset,Integer type,HttpServletRequest request , HttpServletResponse response , Model model){
		User user = ContextUtil.getUser();
		model.addAttribute("user", user);
		model.addAttribute("reset", reset);
		model.addAttribute("type", type);
		return "safecenter/bind1";
	}
	
	//验证第二步
	@RequireUser
	@RequestMapping("/bindOrReset2")
	public String bindOrReset2(String code,Integer reset,Integer type,HttpServletRequest request , HttpServletResponse response , Model model){
		VerifyCode verifyCode = (VerifyCode)request.getSession().getAttribute(Globals.SIGN_SAFECENTER_CODE);
		model.addAttribute("reset", reset);
		model.addAttribute("type", type);
		if(StringUtils.isNotBlank(code)){
			if(verifyCode == null || !StringUtils.equalsIgnoreCase(verifyCode.getCode(), code.toString()) || verifyCode.getExpireTime().before(new Date())) {
				return "redirect:/safecenter/bindOrReset";
			}
			request.getSession().setAttribute(Globals.SIGN_SAFECENTER_CODE, null);//清空发送验证码的session
			return "safecenter/bind2";//跳转到第二步
		}else{
			return "redirect:/safecenter/bindOrReset";
		}
	}
	
	//验证完成
	@RequireUser
	@RequestMapping("/bindOrReset3")
	public String bindOrReset3(String code,Integer reset,Integer type,HttpServletRequest request , HttpServletResponse response , Model model){
		User user = ContextUtil.getUser();
		VerifyCode verifyCode = (VerifyCode)request.getSession().getAttribute(Globals.SIGN_SAFECENTER_CODE);
		model.addAttribute("reset", reset);
		model.addAttribute("type", type);
		if(StringUtils.isNotBlank(code)){
			if(verifyCode == null || !StringUtils.equalsIgnoreCase(verifyCode.getCode(), code.toString()) || verifyCode.getExpireTime().before(new Date())) {
				return "redirect:/safecenter/bindOrReset";//非法操作重新第一步
			}
			//成功验证  保存相应的数据
			String contactname = request.getParameter("contactname");
			if(StringUtils.isNotBlank(contactname)){
				User userby = userService.getUserById(user.getId());
				if(PatternUtils.isEmail(contactname) && contactname.equals(verifyCode.getContact())){
					userby.setEmail(contactname);
					userby.setMailActive(1);//激活
				
				}
				
				if(PatternUtils.isMobile(contactname) && contactname.equals(verifyCode.getContact())){
					userby.setMobile(contactname);
				}
				
				userService.saveOrUpdate(userby);
				ContextUtil.setUser(userby);//刷新session
				
			}else{
				return "redirect:/safecenter/bindOrReset";//非法操作重新第一步
			}
			
			request.getSession().setAttribute(Globals.SIGN_SAFECENTER_CODE, null);//清空发送验证码的session
			return "safecenter/bind3";//跳转到完成
		}else{
			return "redirect:/safecenter/bindOrReset";//非法操作重新第一步
		}
	}
	
	
	
	//发送手机或邮箱验证码
	@ResponseBody
	@RequestMapping("/signcode")
	public AjaxJson signcode(String contact,HttpServletRequest request, HttpServletResponse response){
		AjaxJson ajaxjson=new AjaxJson();
		User user = ContextUtil.getUser();
		String lastcontact=null;
		if(StringUtils.isNotBlank(contact)){
			String code = RandomStringUtils.randomNumeric(6);
			VerifyCode verifyCode = (VerifyCode)request.getSession().getAttribute(Globals.SIGN_SAFECENTER_CODE);
			if(verifyCode!=null){
				if((new Date().getTime()-verifyCode.getCreateTime().getTime()) <60*1000){
					return AjaxJson.error("请1分钟稍后再尝试发送！");
				}
			}
			System.out.println(code);
			//每次发送都更新
				verifyCode = new VerifyCode(code, new Date(), DateUtils.addMinutes(new Date(), 15));
				
				Map<String, String> params = new HashMap();
				params.put("code", code);
				params.put("time", "15");
				List users=new ArrayList();
				UserMsgDto umd=new UserMsgDto();
			if("email".equals(contact) || PatternUtils.isEmail(contact)){
				//发送邮件
				if(PatternUtils.isEmail(contact)){
					umd.setEmail(contact);
				}else{
					umd.setEmail(user.getEmail());
				}
				lastcontact=umd.getEmail();
				verifyCode.setContact(lastcontact);
				users.add(umd);
				request.getSession().setAttribute(Globals.SIGN_SAFECENTER_CODE, verifyCode);
				msgConfigService.sendMessage("SAFECENTER_CODE", params, null, users);
			}else if("mobile".equals(contact) || PatternUtils.isMobile(contact)){
				//发送短信  
				if(PatternUtils.isMobile(contact)){
					umd.setMobile(contact);
				}else{
					umd.setMobile(user.getMobile());
				}
				lastcontact=umd.getMobile();
				verifyCode.setContact(lastcontact);
				users.add(umd);
				request.getSession().setAttribute(Globals.SIGN_SAFECENTER_CODE, verifyCode);
				msgConfigService.sendMessage("SAFECENTER_CODE", params, null, users);
			}else{
				return AjaxJson.error("数据异常，发送失败！");
			}
		}else{
			return AjaxJson.error("发送失败！");
		}
	
		ajaxjson.setObj(lastcontact);
		ajaxjson.setSuccess(true);
		return ajaxjson;
	}
	
	
	//确认验证码
	@ResponseBody
	@RequestMapping("/confirmcode")
	public JSONObject confirmCode(HttpServletRequest request , HttpServletResponse response ,String code){
		JSONObject json =new JSONObject();
		VerifyCode verifyCode = (VerifyCode)request.getSession().getAttribute(Globals.SIGN_SAFECENTER_CODE);
		if(StringUtils.isNotBlank(code)){
			if(verifyCode == null || !StringUtils.equalsIgnoreCase(verifyCode.getCode(), code.toString()) || verifyCode.getExpireTime().before(new Date())) {
				json.put("error", "验证码不正确！");
				return json;
			}
			    json.put("ok", "验证码正确。");
				return json;
		}else{
			json.put("error","操作失败！");
			return json;
		}
	}
	
	//修改密码
	@RequireUser
	@RequestMapping("/resetpassword")
	public String resetPassword(HttpServletRequest request , HttpServletResponse response){
		return "safecenter/resetPassword";
	}
	
	//效验密码
	@ResponseBody
	@RequestMapping("/vlidatePassword")
	public JSONObject vlidatePassword(String password,HttpServletRequest request , HttpServletResponse response){
		User user = ContextUtil.getUser();
		JSONObject json =new JSONObject();
		if(StringUtils.isNotBlank(password)){
			String encodePassword = PasswordUtil.encodePasswordForAZT(password, user.getSalt());
			if(user.getPassword().equals(encodePassword)){
				json.put("ok", "恭喜，密码正确");
			}else{
				json.put("error","密码错误");
			}
		}else{
			json.put("error","密码不能空");
		}
		return json;
	}
	
	@ResponseBody
	@RequestMapping("/savepassword")
	public AjaxJson  savepassword(String password,String newpassword,HttpServletRequest request , HttpServletResponse response){
		User user = ContextUtil.getUser();
		if(StringUtils.isNotBlank(password)){
			String encodePassword = PasswordUtil.encodePasswordForAZT(password, user.getSalt());
			if(user.getPassword().equals(encodePassword)){
				User userby = userService.getUserById(user.getId());
				if(StringUtils.isNotBlank(newpassword)){
					String encodenewpassword = PasswordUtil.encodePasswordForAZT(newpassword, user.getSalt());
					userby.setPassword(encodenewpassword);
					userService.saveOrUpdate(userby);
				}else{
					return AjaxJson.error("新密码不能空。");
				}
			}else{
				return AjaxJson.error("原密码错误。");
			}
		}else{
			return AjaxJson.error("原密码密码不能空。");
		}
		return AjaxJson.success();
	}
	
	//更改密码成功
	@RequireUser
	@RequestMapping("/resetpasswordsuccess")
	public String passwordsuccess(HttpServletRequest request , HttpServletResponse response){
		return "safecenter/resetPasswordSucc";
	}
	
	
	//收货地址
	@RequireUser
	@RequestMapping("/shippingAddress")
	public String shipAddress(HttpServletRequest request , HttpServletResponse response,Model model){
		User user = ContextUtil.getUser();
		//根据userId取收货地址
		List<Address> findUserAddress = addressService.findUserAddress(user.getId());
		model.addAttribute("address", findUserAddress);
		return "safecenter/shippingAddress";
	}
	
	@ResponseBody
	@RequestMapping("/checkusername")
	public JSONObject checkusername(String contactname,HttpServletRequest request , HttpServletResponse response){
		JSONObject json =new JSONObject();
		if(StringUtils.isNotBlank(contactname)){
			if(PatternUtils.isMobile(contactname)){
				User userByMobile = userService.getUserByMobile(contactname);
				if(userByMobile!=null){
					json.put("error", "手机号已经存在！");
				}
			}else if(PatternUtils.isEmail(contactname)){
				User userByEmail = userService.getUserByEmail(contactname);
				if(userByEmail!=null){
					json.put("error", "邮箱已经存在！");
				}
			}
		}

		return json;
	}
	
	
	/**退出公司  用户角色变为注册用户*/
	@ResponseBody
	@RequestMapping("/unbindCompany")
	public AjaxJson unbindCompany (HttpServletRequest request , HttpServletResponse response){
		    User user = ContextUtil.getUser();
		    List<Role> role = ContextUtil.getRoles();
		    Role newRole = userPermissionService.quitCompany(user,role);
			//刷新session
			ContextUtil.setUser(user);
			ContextUtil.setCurrentRole(newRole);
			return AjaxJson.success();
	}
	
}
